import { _decorator, Component, EventKeyboard, Input, input, KeyCode, log, Node } from 'cc';
const { ccclass, property } = _decorator;

enum Dir {
    k5 = 5,
    k8 = 8,
    k9 = 9,
    k6 = 6,
    k3 = 3,
    k2 = 2,
    k1 = 1,
    k4 = 4,
    k7 = 7,

}

export enum KeyBoardConfigEvent {
    keyDown = 'keyDown'
}

@ccclass('KeyBoardConfig')
export class KeyBoardConfig extends Component {
    private _current: Dir = Dir.k5;
    private _isChange: boolean = false;

    [key: number]: boolean
    start() {
        input.on(Input.EventType.KEY_DOWN, this.keyDown, this);
        input.on(Input.EventType.KEY_UP, this.keyUp, this);
    }

    protected onDestroy(): void {
        input.off(Input.EventType.KEY_DOWN, this.keyDown, this);
        input.off(Input.EventType.KEY_UP, this.keyUp, this);
    }


    keyDown(key: EventKeyboard) {
        this[key.keyCode] = true;
        this.changeKey();
    }

    keyUp(key: EventKeyboard) {
        this[key.keyCode] = false;
        this.changeKey();
    }

    changeKey() {
        let key = this.getDir();
        if (this._current != key) {
            this._current = key;
            console.log(key);
            this.node.emit(KeyBoardConfigEvent.keyDown, this, this._current);
        }
    }

    getDir(): Dir {
        if (this.getUp() && this.getRight()) {
            return Dir.k9;
        }
        else if (this.getRight() && this.getDown()) {
            return Dir.k3
        }
        else if (this.getLeft() && this.getDown()) {
            return Dir.k1
        }
        else if (this.getLeft() && this.getUp()) {
            return Dir.k7
        }

        else if (this.getUp()) {
            return Dir.k8;
        }
        else if (this.getRight()) {
            return Dir.k6;
        }
        else if (this.getDown()) {
            return Dir.k2;
        }
        else if (this.getLeft()) {
            return Dir.k4;
        }
        else {
            return Dir.k5;
        }
    }

    getUp() {
        return this[KeyCode.KEY_W] || this[KeyCode.ARROW_UP];
    }

    getRight() {
        return this[KeyCode.KEY_D] || this[KeyCode.ARROW_RIGHT];
    }

    getDown() {
        return this[KeyCode.KEY_S] || this[KeyCode.ARROW_DOWN];
    }

    getLeft() {
        return this[KeyCode.KEY_A] || this[KeyCode.ARROW_LEFT];
    }
}


